import { Group, LoadingManager } from 'three'
import type { DirBlobDataItem } from '../../resource-management/entities'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { KTX2Loader } from 'three/examples/jsm/Addons.js'
import { MeshoptDecoder } from 'three-stdlib'

export class ThreeGLTFLoader {
  public constructor() {}

  public async loadModel(url: string, dirBlobData?: DirBlobDataItem): Promise<Group> {
    // 写一个加载gltf文件的代码
    const modelGroup = new Group()

    const manager = new LoadingManager()
    if (dirBlobData) {
      const blobPath_blobUrlMap = dirBlobData.blobPathUrlMap
      // 设置tdsloader资源查找代理，去blobPath_blobUrlMap寻找资源
      manager.setURLModifier((innerUrl) => {
        // console.log('[o] need url:', innerUrl)
        if (blobPath_blobUrlMap.has(innerUrl)) {
          console.log('[√] modifier success:', innerUrl, blobPath_blobUrlMap.get(innerUrl))
          return blobPath_blobUrlMap.get(innerUrl) as string
        } else {
          console.warn('[x] modifier failed:', innerUrl)
          return innerUrl
        }
      })
    }

    // 使用 Three.js 提供的 GLTFLoader 加载模型
    const loader = new GLTFLoader(manager)
    const ktx2Loader = new KTX2Loader()
    const meshopt = MeshoptDecoder()
    loader.setKTX2Loader(ktx2Loader)

    loader.setMeshoptDecoder(meshopt)
    const gltf = await loader.loadAsync(url) // 异步加载 GLTF 模型

    // 将加载的模型添加到 Group 中
    modelGroup.add(gltf.scene)

    console.log('loadGLTFModel success:', gltf.scene)

    return modelGroup
  }
}
